define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'customer_demand/index' + location.search,
                    add_url: 'customer_demand/add',
                    edit_url: 'customer_demand/edit',
                    del_url: 'customer_demand/del',
                    multi_url: 'customer_demand/multi',
                    import_url: 'customer_demand/import',
                    table: 'customer_demand',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                fixedColumns: true,
                fixedRightNumber: 1,
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {field: 'name', title: __('Name'), operate: 'LIKE'},
                        {field: 'product_id', title: __('Product_id')},
                        {field: 'customer_id', title: __('Customer_id')},
                        {field: 'width', title: __('Width'), operate:'BETWEEN'},
                        {field: 'length', title: __('Length'), operate:'BETWEEN'},
                        {field: 'unit', title: __('Unit'), searchList: {"平方米":__('平方米'), "支":__('支')}, formatter: Table.api.formatter.normal},
                        {field: 'product_model', title: __('Product_model'), operate: 'LIKE'},
                        {field: 'unit_price', title: __('Unit_price'), operate:'BETWEEN'},
                        {field: 'tax_rate', title: __('Tax_rate'), operate:'BETWEEN'},
                        {field: 'create_time', title: __('Create_time'), operate:'RANGE', addclass:'datetimerange', autocomplete:false},
                        {field: 'update_time', title: __('Update_time'), operate:'RANGE', addclass:'datetimerange', autocomplete:false},
                        {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate}
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        add: function () {
            // 获取input标签product-info
            var productInfoInput = document.getElementById('product-info');
            // 使用jQuery给c-product_id绑定change事件
            $('#c-product_id').on('change', function() {
                Controller.updateProductInfo();
            })
            Controller.api.bindevent();
        },
        edit: function () {
            // 使用jQuery给c-product_id绑定change事件
            $('#c-product_id').on('change', function() {
                Controller.updateProductInfo();
            })
            Controller.api.bindevent();
            Controller.updateProductInfo();
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));

                // 通过含税单价和税率计算单价、税额
                function calcUnitPriceFromTaxWithTax() {
                    var unitPriceWithTax = parseFloat($('#c-unit_price_with_tax').val()) || 0;
                    var taxRate = parseFloat($('#c-tax_rate').val()) || 0;

                    if (taxRate > 0 && unitPriceWithTax > 0) {
                        var unitPrice = unitPriceWithTax / (1 + taxRate / 100);
                        var taxAmount = unitPrice * (taxRate / 100);

                        // 更新单价（只读显示）
                        $('#c-unit_price').val(unitPrice.toFixed(2));
                        // 更新税额
                        $('#c-tax_amount').val(taxAmount.toFixed(2));
                    } else if (unitPriceWithTax > 0) {
                        // 如果税率为0，税额为0，单价等于含税单价
                        $('#c-unit_price').val(unitPriceWithTax.toFixed(2));
                        $('#c-tax_amount').val('0.00');
                    }
                }

                // 使用FastAdmin标准事件绑定方式
                $(document).on("change", "#c-unit_price_with_tax", function(){
                    var unitPriceWithTax = parseFloat($(this).val());
                    if (!isNaN(unitPriceWithTax) && unitPriceWithTax >= 0) {
                        calcUnitPriceFromTaxWithTax();
                    }
                });

                $(document).on("change", "#c-tax_rate", function(){
                    var taxRate = parseFloat($(this).val());
                    var unitPriceWithTax = parseFloat($('#c-unit_price_with_tax').val());

                    if (!isNaN(taxRate) && taxRate >= 0 && !isNaN(unitPriceWithTax) && unitPriceWithTax > 0) {
                        calcUnitPriceFromTaxWithTax();
                    }
                });

                // 初始化计算
                calcUnitPriceFromTaxWithTax();
            }
        },
        updateProductInfo: function() {
            var productInfoInput = document.getElementById('product-info');
            var productId = $('#c-product_id').val();
            if (productId) {
                // 发送AJAX请求获取产品信息
                $.ajax({
                    url: 'clothmaking_product/getProductInfoById', // 需要在控制器中创建此方法
                    type: 'GET',
                    data: {id: productId},
                    success: function(response) {
                        if (response) {
                            productInfoInput.value = response.name+'  '+response.number+'  '+response.alias+'  '+response.specifications; // 设置产品信息
                        } else {
                            productInfoInput.value = '未找到产品信息';
                        }
                    },
                    error: function() {
                        productInfoInput.value = '获取产品信息失败';
                    }
                });
            } else {
                productInfoInput.value = '';
            }
        }
    };
    return Controller;
});
